﻿using FileSC.Configs;
using FileSC.DB.Entities;
using LiteDB;
using System;
using System.Collections.Generic;

namespace FileSC.DB.Database
{
    public class OpenJobDB : IDisposable
    {
        internal LiteDatabase db { get; set; }
        internal ILiteCollection<OpenJobInfo> tb_info { get; set; }
        public OpenJobDB()
        {
            var db_path = AppConfig.Text("上传记录库");

            db = new LiteDatabase(db_path);
            tb_info = db.GetCollection<OpenJobInfo>();
            tb_info.EnsureIndex(x => x.JobID, true);
            tb_info.EnsureIndex(x => x.CreateTime);
            tb_info.EnsureIndex(x => x.UpdatedTime);
        }
        public void Dispose()
        {
            db.Dispose();
        }

        public IEnumerable<OpenJobInfo> GetInfos()
        {
            return tb_info.FindAll();
        }

        public void Update(OpenJobInfo info)
        {
            DBHost.Link(info);
            tb_info.Upsert(info);
            db.Commit();
        }

        public OpenJobInfo Update(Guid id, Func<OpenJobInfo, OpenJobInfo> func)
        {
            var info = FindByInfoId(id);
            info = func(info);
            info.UpdatedTime = DateTime.Now;
            Update(info);
            db.Commit();
            return info;
        }

        public OpenJobInfo FindByInfoId(Guid id)
        {
            var info = tb_info.FindById(id);
            return info;
        }
    }
}
